import { HttpException, HttpStatus, Injectable } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { Repository } from 'typeorm'

import { JwtTool } from '@/shared/utils/tool'

import { LoginUserDto } from './dto/user.dto'
import { User } from './entities/user.entity'

@Injectable()
export class UserService {
  // 这里需要 module 导入 UtilsModule
  // private jwt = new JwtTool();

  constructor(
    @InjectRepository(User)
    private readonly usersRepository: Repository<User>, // private readonly analyticsService: AnalyticsService,
    private readonly jwt: JwtTool,
  ) {}

  async login(data: LoginUserDto) {
    const findUserData = await this.usersRepository.findOne({
      where: {
        username: data.username,
      },
      select: ['userId', 'username', 'password'],
    })
    if (!findUserData) {
      throw new HttpException('用户不存在', HttpStatus.BAD_REQUEST)
    }

    const isPasswordValid = data.password === findUserData.password

    if (!isPasswordValid) {
      throw new HttpException('密码错误', HttpStatus.BAD_REQUEST)
    }
    const token = this.jwt.generateToken({
      ...findUserData,
      password: undefined,
    })

    return token
  }

  findAll(): Promise<User[]> {
    return this.usersRepository.find()
  }
}
